package com.itps.fileservice.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.UUID;

@RestController
@RequestMapping("/picture")
public class PictureController {

    // 从 application.yml 读取存储路径，如果没有配置默认路径是 user.home/uploads/
    @Value("${file.upload.dir:${user.home}/uploads/}")
    private String uploadDir;

    // 访问前缀 默认是 http://localhost:8999/files/
    @Value("${file.access.url:http://localhost:8999/files/}")
    private String accessUrl;

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "上传失败，文件为空";
        }

        // 日期分目录
        String datePath = LocalDate.now().toString();
        String originalFilename = file.getOriginalFilename();
        String suffix = (originalFilename != null && originalFilename.contains("."))
                ? originalFilename.substring(originalFilename.lastIndexOf("."))
                : "";

        // 新文件名
        String newFilename = UUID.randomUUID() + suffix;

        // 保存路径
        File saveDir = new File(uploadDir + datePath);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }

        // 原文件路径
        File originalFile = new File(saveDir, "original_" + newFilename);
        file.transferTo(originalFile);

        // 压缩后的文件路径
        File compressedFile = new File(saveDir, newFilename);

        // 使用 Hutool 压缩图片
        try (InputStream in = FileUtil.getInputStream(originalFile)) {
            ImgUtil.scale(in, FileUtil.getOutputStream(compressedFile), 0.9f);
        }

        // 压缩完成后删除原始文件（可选）
        originalFile.delete();

        // 返回可访问的 URL
        return accessUrl + datePath + "/" + newFilename;
    }
}